<template>
  <div class="rewelding-frequency">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="后行钢卷号" style="width:200px">
          <el-input v-model="searchForm.bentID" placeholder="输入" />
        </el-form-item>
        <el-form-item label="后行钢钢种" style="width:200px">
          <el-input v-model="searchForm.bsteelGrade" placeholder="输入" />
        </el-form-item>

        <el-form-item label="是否重焊">
          <el-select
            v-model="searchForm.weldTimes"
            placeholder="Select"
            size="small"
            style="width: 80px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班次" style="width:120px" >
          <el-select
            v-model="searchForm.shift"
            placeholder="Select"
            size="small"
            style="width: 80px"
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班组" style="width:120px">
          <el-select
            v-model="searchForm.crew"
            placeholder="Select"
            size="small"
            style="width: 80px"
          >
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="输入"
            format="YYYY-MM-DD HH:mm:ss"
          />
          至
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="输入"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <!-- <el-button type="primary" @click="handleExport">导出</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" height="calc(100vh - 180px)" :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
        :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
        :row-style="{ background: '#0f2142' }">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="weldTimes" label="焊接次数" width="110" align="center">
        <template #default="scope">
          <span :style="scope.row.weldTimes > 1 ? 'color: #ff4d4f; font-weight: bold;' : ''">{{ scope.row.weldTimes }}</span>
        </template>
      </el-table-column>
      
      <!-- 后行钢 -->
      <el-table-column label="后行钢" align="center">
        <el-table-column prop="bentID" label="钢卷号" width="160" align="center">
          <template #default="scope">
            <span :style="scope.row.weldTimes > 1 ? 'color: #ff4d4f; font-weight: bold;' : ''">{{ scope.row.bentID }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="binMatThick" label="入口厚度[mm]" width="140" align="center" />
        <el-table-column prop="binMatWidth" label="入口宽度[mm]" width="140" align="center" />
        <el-table-column prop="bsteelGrade" label="钢牌号" width="120" align="center" />
        <el-table-column prop="btrimFlag" label="是否切边" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.btrimFlag=='0'?'否':'是' }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 前行钢 -->
      <el-table-column label="前行钢" align="center">
        <el-table-column prop="fentID" label="钢卷号" width="160" align="center" />
        <el-table-column prop="finMatThick" label="入口厚度[mm]" width="140" align="center" />
        <el-table-column prop="finMatWidth" label="入口宽度[mm]" width="140" align="center" />
        <el-table-column prop="fsteelGrade" label="钢牌号" width="120" align="center" />
        <el-table-column prop="ftrimFlag" label="是否切边" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.ftrimFlag=='0'?'否':'是' }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="" label="焊接时长(s)" width="120" align="center"></el-table-column>

      <el-table-column prop="createTime" label="焊接时间" width="230" align="center">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="shift" label="班次" width="110" align="center">
        <template #default="scope">
          <span>{{ scope.row.shift=='1'?'白':'夜' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="crew" label="班组" width="110" align="center">
        <template #default="scope">
          <span>{{ scope.row.crew=='A'?'甲':scope.row.crew=='B'?'乙':scope.row.crew=='C'?'丙':'丁' }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus';

const route = useRoute();

// 时间格式转换函数：将正常时间转换为数据库格式 (YYYY-MM-DD-HH.mm.ss.SSSSSS)
const formatTimeToDb = (time: string | Date): string => {
  if (!time) return '';
  const date = typeof time === 'string' ? new Date(time) : time;
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  const milliseconds = String(date.getMilliseconds()).padStart(3, '0') + '000';
  return `${year}-${month}-${day}-${hours}.${minutes}.${seconds}.${milliseconds}`;
};

// 搜索表单数据
const searchForm = reactive({
  bentID: '',
  bsteelGrade: '',
  startTime: '',
  endTime: '',
  weldTimes:1,
  crew:'E',
  shift:2
})

const options = [
  {
    value: 2,
    label: '全部',
  },
  {
    value: 0,
    label: '否',
  },
  {
    value: 1,
    label: '是',
  },
]

const options1 = [
  {
    value: 2,
    label: '全部',
  },
  {
    value: 1,
    label: '白',
  },
  {
    value: 0,
    label: '夜',
  }
]

const options2 = [
  {
    value: "E",
    label: '全部',
  },
  {
    value: "A",
    label: '甲',
  },
  {
    value: "B",
    label: '乙',
  },
  {
    value: "C",
    label: '丙',
  },
  {
    value: "D",
    label: '丁',
  },
  
]

// 表格数据
const tableData = ref([
  {
    weldTimes:"",
    bentID:"",
    bsteelGrade:"",
    binMatThick:"",
    binMatWidth:"",
    fentID:"",
    fsteelGrade:"",
    finMatThick:"",
    finMatWidth:"",
    prodStartTime:"",
    crew:""
  }
  // ... 其他数据
])

// 生命周期钩子
onMounted(() => {
  // 自动读取路由参数
  const { bentID, weldTimes } = route.query;
  if (bentID) searchForm.bentID = String(bentID);
  if (weldTimes !== undefined) searchForm.weldTimes = Number(weldTimes);
  fetchTableData();
});



// --- Pagination --- 
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: tableData.value.length
});

// 搜索方法
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  pagination.currentPage = 1;
  fetchTableData();
}

// 获取表格数据
const fetchTableData = async () => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
      entid:searchForm.bentID,
      bsteelGrade:searchForm.bsteelGrade,
      startDate: searchForm.startTime ? formatTimeToDb(searchForm.startTime) : '',
      endDate: searchForm.endTime ? formatTimeToDb(searchForm.endTime) : '',
      weldTimes:searchForm.weldTimes,
      shift:searchForm.shift==2?'':searchForm.shift,
      crew:searchForm.crew=='E'?'':searchForm.crew

    };

    // 移除未定义的参数，避免发送空字符串
    Object.keys(params).forEach(key => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    console.log("Fetching data with params:", params);
    const response = await acidRollingApi.getReWeldList(params);
    console.log("API Response:", response);

    // Correctly access data from response.data if 'response' is an AxiosResponse
    const responseData = response.data;

    if (
      responseData &&
      responseData.data &&
      Array.isArray(responseData.data)
    ) {
      tableData.value = responseData.data.map((item: any) => ({
        ...item, // Keep other original fields if needed for detail view
        binMatThick: item.binMatThick !== undefined && item.binMatThick !== null && item.binMatThick !== '' ? Number(item.binMatThick).toFixed(1) : '',
        finMatThick: item.finMatThick !== undefined && item.finMatThick !== null && item.finMatThick !== '' ? Number(item.finMatThick).toFixed(1) : '',
        binMatWidth: item.binMatWidth !== undefined && item.binMatWidth !== null && item.binMatWidth !== '' ? Math.round(Number(item.binMatWidth)) : '',
        finMatWidth: item.finMatWidth !== undefined && item.finMatWidth !== null && item.finMatWidth !== '' ? Math.round(Number(item.finMatWidth)) : '',
        createTime:item.createTime.substring(0,19)
      }));
      console.log(tableData.value);
      pagination.total = responseData.count || responseData.data.length; // Use responseData.count for total
      ElMessage.success(responseData.msg || "查询成功");
    } else {
      ElMessage.info(
        responseData?.msg ||
          (response as any)?.msg ||
          "未查询到数据或响应格式不正确"
      );
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    console.error("获取数据失败:", error);
    // Try to get error message from error.response.data.msg or error.data.msg
    const errorMessage =
      error.response?.data?.msg ||
      error.data?.msg ||
      error.msg ||
      error.message ||
      "获取数据失败";
    ElMessage.error(errorMessage);
    tableData.value = [];
    pagination.total = 0;
  }
};

// 重置方法
const handleReset = () => {
  searchForm.bentID = ''
  searchForm.bsteelGrade = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
}

// 导出方法
const handleExport = () => {
  // TODO: 实现导出逻辑

}

// 页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTableData();
};
// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTableData();
};

// 时间格式转换函数：将数据库格式转换为正常显示格式 (YYYY-MM-DD HH:mm:ss)
const formatTimeFromDb = (dbTime: string): string => {
  if (!dbTime) return '-';
  try {
    // 处理多种格式：
    // 1. 2025-11-18 00:00:00.0 (标准格式)
    // 2. 2025-11-16-23.34.36.849386 (特殊格式)
    
    // 先尝试标准格式（包含空格和冒号）
    if (dbTime.includes(' ') && dbTime.includes(':')) {
      // 格式：2025-11-18 00:00:00.0 或 2025-11-18 00:00:00
      const timeStr = dbTime.split('.')[0]; // 去掉毫秒部分
      return timeStr;
    }
    
    // 处理特殊格式：2025-11-16-23.34.36.849386
    const parts = dbTime.split('-');
    if (parts.length >= 4) {
      const datePart = `${parts[0]}-${parts[1]}-${parts[2]}`;
      const timePart = parts[3].replace(/\./g, ':').substring(0, 8);
      return `${datePart} ${timePart}`;
    }
    
    return dbTime;
  } catch (e) {
    return dbTime || '-';
  }
};

function formatDateTime(val: string | number): string {
  if (!val) return '-';
  const strVal = String(val);
  // 使用统一的格式化函数
  return formatTimeFromDb(strVal);
}
</script>

<style scoped>
.rewelding-frequency {
  background-color: #0a1a3a;
  color: #c0c4cc;
  padding: 10px;
  height: 100%;
  /* Use 100% for layout within router-view */
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
  font-size: 13px;
  overflow: hidden;
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
  display: flex;
  flex-direction: column;
}

.search-form {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  flex-shrink: 0;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

:deep(.el-form-item__label){
  color: #c0c4cc;
  white-space: nowrap;
  /* min-width: 65px; */
  /* Match LayOutJudge */
  text-align: right;

}

:deep(.el-table__header) th {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-input__wrapper) {
  width: 180px;
}

:deep(.el-date-editor.el-input) {
  width: 180px;
}

:deep(.el-table),
:deep(.el-table__body),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__empty-block) {
  background: linear-gradient(135deg, #183c7e 0%, #0a1a3a 100%) !important;
}
:deep(.el-table th),
:deep(.el-table td) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr:hover > td) {
  background-color: #223a6b !important;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  z-index: -1;
}


:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}
:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
  border-bottom:none;
}


/* --- Pagination Panel (Styles should be consistent) --- */
.pagination-panel {
  background-color: #1c2d5a;
  padding: 8px 15px;
  border-radius: 3px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}
:deep(.el-pagination) {
  background-color: transparent !important;
}
:deep(.el-pagination__total),
:deep(.el-pagination__sizes),
:deep(.el-pagination__jump),
:deep(.el-pagination__editor),
:deep(.el-pagination button),
:deep(.el-pager li) {
  background-color: #1c2d5a !important;
  color: #7ec7ff !important;
  border: none !important;
}
:deep(.el-pager li.is-active) {
  background-color: #2979ff !important;
  color: #fff !important;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

.custom-input,
.custom-select,
.range-input,
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  height: 28px;
  line-height: 28px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 13px !important;
}

:deep(.custom-select .el-select__placeholder),
:deep(.custom-select .el-select__caret) {
  color: #c0c4cc;
}
.rewelding-frequency>*:not(:last-child) {
  margin-bottom: 15px;
}
.el-form--inline .el-form-item{
  margin-right:12px
}
</style>
